﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;
namespace DHQGHN.PM0.Controllers.Admin
{
    public class AdmUnitController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AdmUnitController));  //Declaring Log4Net
        public const int REQUEST_ACTIVE = 1;
        AdmUnitBO admUnitBO;
        // GET: /AdmUnit/
        //public ActionResult AdmUnit(AdmUnitModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string curentID = null)
        public ActionResult Index(AdmUnitModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string curentID = null)
        {
            var model = new DataPage<AdmUnitModel>();
            try
            {
                if (string.IsNullOrEmpty(curentID))
                {
                    curentID = string.Empty;
                }
                if (a == null) a = new AdmUnitModel();

                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[34] = "active";
                
                a.Deleted = 2;
                a.Levels = 0;

                model = search(a, pageIndex, curentID, false);
                ViewBag.lstProvince = getListProvince();
                ViewBag.lstDistrict = getListDistrictName(a.Province_Code);
                ViewBag.ListLevel = GetListLevel();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }
            return View("~/Views/AdmUnit/AdmUnit.cshtml", model);
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionActive(string id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    admUnitBO = new AdmUnitBO();
                    bool result = admUnitBO.activeAdmUnit(id, REQUEST_ACTIVE);
                    if (result)
                    {
                        LogStream.Write(GlobalInfo.User.UserName,
                          CommonData.AppName,
                          GetFunction(),
                          CommonData.GetListId(new string[] { id }),
                          Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200("Khôi phục đơn vị hành chính thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }
            return null;
        }

        // Hien thi form them moi don vi hanh chinh 
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateAdmUnit(string id, string provinceid)
        {
            AdmUnitModel model = null;
            try
            {
                if (!String.IsNullOrEmpty(id))
                {
                    admUnitBO = new AdmUnitBO();
                    model = new AdmUnitModel(admUnitBO.GetAdmUnitById(id));
                    if (model.Levels == 2)
                    {
                        model.Code = model.District_Code;
                    }
                    else if (model.Levels == 3)
                    {
                        model.Code = model.Commune_Code;
                    }
                }
                if (model == null)
                {
                    model = new AdmUnitModel();
                }
                ViewBag.lstProvince = getListProvince();
                ViewBag.lstDistrict = getListDistrictName(model.Province_Code);
                ViewBag.ListLevel = GetListLevel();
                ViewBag.ADMType = GetADMTypeByLevel(model.Levels);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/AdmUnit/_AdmUnitModel.cshtml", model);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult actionSearch(AdmUnitModel aModel = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new AdmUnitModel();

                if (string.IsNullOrEmpty(currentId))
                {
                    currentId = string.Empty;
                }
                var model = search(aModel, pageIndex, currentId, false);
                ViewBag.lstProvince = getListProvince();
                ViewBag.lstDistrict = getListDistrictName(aModel.Province_Code);
                return PartialView("~/Views/AdmUnit/_AdmUnitList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public JsonResult RetrieveDistricts(string Province_Code)
        {
            try
            {
                var listDistricts = getListDistrictName(Province_Code);
                return Json(listDistricts, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }

        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        // Thêm mới đơn vị hành chính 
        public ActionResult actionCreateOrUpdateAdmunit(AdmUnitModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    if (model == null)
                    {
                        model = new AdmUnitModel();
                    }

                    AdmUnitModel newModel = new AdmUnitModel()
                    {
                        Adm_Unit_Id = model.Adm_Unit_Id,
                        Adm_Name = model.Adm_Name,
                        Adm_Type = model.Adm_Type,
                        Levels = model.Levels,
                        Descriptions = model.Descriptions
                    };

                    switch (model.Levels)
                    {
                        case 1:
                            newModel.Province_Code = model.Code;
                            newModel.Province_Name = model.Adm_Name;
                            newModel.Code = model.Code;
                            break;
                        case 2:
                            newModel.Province_Code = model.Province_Code;
                            newModel.Province_Name = model.Province_Name;
                            newModel.Code = String.Concat(model.Province_Code, model.Code);
                            newModel.District_Name = model.Adm_Name;
                            newModel.District_Code = model.Code;
                            newModel.P_Code = model.Province_Code;
                            break;
                        default:
                            newModel.Province_Code = model.Province_Code;
                            newModel.Province_Name = model.Province_Name;
                            newModel.District_Code = model.District_Code;
                            newModel.District_Name = model.District_Name;
                            newModel.Code = String.Concat(model.Province_Code, model.District_Code, model.Code);
                            newModel.Commune_Name = model.Adm_Name;
                            newModel.Commune_Code = model.Code;
                            newModel.P_Code = String.Concat(model.Province_Code, model.District_Code);
                            break;

                    }

                    admUnitBO = new AdmUnitBO();
                    bool result = admUnitBO.createOrUpdateAdmUnit(newModel.toDALModel());
                    if (result)
                    {
                        LogStream.Write<AdmUnitModel>(GlobalInfo.User.UserName,
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateAdmunit", newModel);

                        if (!(String.IsNullOrEmpty(model.Adm_Unit_Id) || String.IsNullOrWhiteSpace(model.Adm_Unit_Id)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật đơn vị hành chính thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới đơn vị hành chính thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        //Xóa đơn vị hành chính 
        public ActionResult actionDelete(string[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    admUnitBO = new AdmUnitBO();
                    bool result = admUnitBO.deleteAdmUnit(id);
                    if (result)
                    {
                        LogStream.Write(GlobalInfo.User.UserName,
                           CommonData.AppName,
                           GetFunction(),
                           CommonData.GetListId(id),
                           Resources.Localization.ActionDeleteCaption + " - actionDelete");
                        return Json(JsonResponse.Json200("Xóa đơn vị hành chính thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json200("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<AdmUnitModel> search(AdmUnitModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                admUnitBO = new AdmUnitBO();
                var DALModel = admUnitBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<AdmUnitModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.AdmUnitModel admunit in lstItem)
                {
                    models.Data.Add(new AdmUnitModel(admunit));
                }
                AdmUnitModel model = null;
                if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => Equals(user.Adm_Unit_Id, currentId));
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = aModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "AdmUnit",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "admunit-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception)
            {
                throw;
            }
        }

        //Lấy ra danh sach tên tỉnh theo mã tỉnh
        private IEnumerable<SelectListItem> getListProvince()
        {
            List<SelectListItem> lstItems1 = new List<SelectListItem>();
            try
            {
                admUnitBO = new AdmUnitBO();
                var lstType = admUnitBO.GetAllProvince();

                lstItems1.Add(new SelectListItem
                {
                    Value = string.Empty,
                    Text = Resources.Localization.TextDisplayFirst_All
                });
                foreach (var type in lstType)
                {
                    lstItems1.Add(new SelectListItem
                    {
                        Value = type.Province_Code,
                        Text = type.Province_Name
                    });
                }
                return new SelectList(lstItems1, "Value", "Text");
            }
            catch (NullReferenceException ex)
            {
                logger.Error(ex.ToString());
                return lstItems1;
            }

        }

        //Lấy ra danh sách tên huyện theo mã huyện 
        private IEnumerable<SelectListItem> getListDistrictName(string provinceid)
        {
            try
            {
                admUnitBO = new AdmUnitBO();
                var lstType = admUnitBO.GetAllDistrict(provinceid);
                List<SelectListItem> lstItems = new List<SelectListItem>();

                if (!String.IsNullOrEmpty(provinceid))
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = string.Empty,
                        Text = Resources.Localization.TextDisplayFirst_All
                    });

                    foreach (var type in lstType)
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = type.District_Code,
                            Text = type.District_Name
                        });
                    }
                }
                else
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = string.Empty,
                        Text = Resources.Localization.TextDisplayFirst_SelectDistrict
                    });
                }
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception)
            {
                throw;
            }
        }

        //Kiểm tra tên đơn vị hành chính đã tồn tại chưa
        public JsonResult CheckExistAdmUnitName(string Adm_Name, string Adm_Unit_Id)
        {
            try
            {

                AdmUnitModel admunitModel = new AdmUnitModel()
                {
                    Adm_Name = Adm_Name
                };

                var model = search(admunitModel, 0, string.Empty, true);
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (AdmUnitModel admunit in lstItem)
                    {
                        if (!String.IsNullOrEmpty(Adm_Unit_Id) || !String.IsNullOrWhiteSpace(Adm_Unit_Id))
                        {
                            if (!Equals(admunit.Adm_Unit_Id, Adm_Unit_Id))
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.AdmUnitNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã đơn vị hành chính đã tồn tại chưa
        public JsonResult CheckExistAdmUnitCode(string code, string Adm_Unit_Id)
        {
            AdmUnitModel admunitModel = new AdmUnitModel()
            {
                Code = code
            };
            var model = search(admunitModel, 0, string.Empty, true);
            var isExist = false;
            if (model.Data.Any())
            {
                var lstItem = model.Data;
                foreach (AdmUnitModel admunit in lstItem)
                {
                    if (!String.IsNullOrEmpty(Adm_Unit_Id) || !String.IsNullOrWhiteSpace(Adm_Unit_Id))
                    {
                        if (!Equals(admunit.Adm_Unit_Id, Adm_Unit_Id))
                        {
                            isExist = true;
                            break;
                        }
                    }
                    else
                    {
                        //Kiem tra truong hop them moi
                        isExist = true;
                        break;
                    }
                }
            }
            if (isExist)
            {
                return Json(Resources.Localization.AdmUnitCodeExist);
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }

        [AjaxValidateAntiForgeryToken]
        public JsonResult GetADMType(int level)
        {
            SelectList listItem = GetADMTypeByLevel(level);

            return Json(listItem);
        }

        private SelectList GetADMTypeByLevel(int? level)
        {
            SelectListItem caption = new SelectListItem
            {
                Value = string.Empty,
                Text = Resources.Localization.TextSelectADMUnit
            };

            if (level == 1)
            {
                return new SelectList(new[] {
                    caption,
                    new SelectListItem { Value = "TI", Text = Resources.Localization.TextCommune},
                    new SelectListItem { Value = "TP", Text = Resources.Localization.TextCity},
                }, "Value", "Text", "TI");
            }
            else if (level == 2)
            {
                return new SelectList(new[] {
                    caption,
                    new SelectListItem { Value = "QU", Text = Resources.Localization.TextQuan},
                    new SelectListItem { Value = "HU", Text = Resources.Localization.TextHuyen},
                    new SelectListItem { Value = "TX", Text = Resources.Localization.TextThiXa},
                    new SelectListItem { Value = "TP", Text = Resources.Localization.TextCity},
                }, "Value", "Text", "QU");
            }
            else if (level == 3)
            {
                return new SelectList(new[] {
                    caption,
                    new SelectListItem { Value = "XA", Text = Resources.Localization.TextXa},
                    new SelectListItem { Value = "PH", Text = Resources.Localization.TextPhuong },
                    new SelectListItem { Value = "TT", Text = Resources.Localization.TextThiTran},
                }, "Value", "Text", "XA");
            }

            return new SelectList("", "Value", "Text");
        }

        private SelectList GetListLevel()
        {
            SelectList lstLevel = new SelectList(new[] {
                new SelectListItem { Value = "", Text = Resources.Localization.TextSelectADMUnitLevel},
                new SelectListItem { Value = "1", Text = Resources.Localization.TextTinhThanhPhoThuocTrungUong},
                new SelectListItem { Value = "2", Text = Resources.Localization.TextQuanHuyenThiXaThanhPhoThuocTinh},
                new SelectListItem { Value = "3", Text = Resources.Localization.TextXaPhuongThiTran}
            }, "Value", "Text", 0);

            return lstLevel;
        }

        private static string GetFunction()
        {
            return "Danh mục đơn vị hành chính";
        }


    }
}